import os
import tkinter as tk
from tkinter import messagebox

import ttkbootstrap as ttkb
from tinydb import TinyDB, Query
from ttkbootstrap.constants import *

from app.util.annotation_util import annotate, ClassInfo
from app.view.base_view import View


@annotate(ClassInfo(name="系统设置", category="setting"))
class SettingsView(View):

    def __init__(self, parent, controller):
        super().__init__(parent, controller)
        # 确保配置文件目录存在
        if not os.path.exists('config'):
            os.makedirs('config')

        # 初始化数据库
        self.db = TinyDB('config/settings.json')
        self.settings_table = self.db.table('app_settings')

        # 加载保存的设置，如果没有则使用默认值
        self.load_settings()

        # 创建设置界面
        self._create_widgets()

        # 应用已保存的设置
        self.apply_saved_settings()

    def load_settings(self):
        """从数据库加载设置，如果没有则使用默认值"""
        settings = self.settings_table.get(Query().id == 1)

        if settings:
            self.settings = settings
        else:
            # 默认设置
            self.settings = {
                'id': 1,
                'theme': 'litera',
                'font_family': 'SimHei',
                'font_size': 10,
                'window_width': 800,
                'window_height': 600,
                'allow_scaling': True,
                'system_name': '我的应用',
                'auto_save': True
            }
            self.settings_table.insert(self.settings)

    def _create_widgets(self):
        """创建所有设置界面组件"""
        # 标题
        title_label = ttkb.Label(
            self,
            text="系统设置",
            font=('SimHei', 16, 'bold')
        )
        title_label.pack(pady=(0, 20))

        # 创建一个笔记本（标签页）控件
        notebook = ttkb.Notebook(self)
        notebook.pack(fill=BOTH, expand=True)

        # 外观设置标签页
        appearance_frame = ttkb.Frame(self)
        notebook.add(appearance_frame, text="外观设置")

        # 系统设置标签页
        system_frame = ttkb.Frame(self)
        notebook.add(system_frame, text="系统设置")

        # 填充外观外观设置标签页
        self.create_appearance_settings(appearance_frame)

        # 填充系统设置标签页
        self.create_system_settings(system_frame)

        # 按钮区域
        buttons_frame = ttkb.Frame(self)
        buttons_frame.pack(fill=X, pady=20)

        # 保存按钮
        save_btn = ttkb.Button(
            buttons_frame,
            text="保存设置",
            command=self.save_settings,
            bootstyle=SUCCESS
        )
        save_btn.pack(side=RIGHT, padx=5)

        # 取消按钮
        # cancel_btn = ttkb.Button(
        #     buttons_frame,
        #     text="取消",
        #     command=self.quit,
        #     bootstyle=OUTLINE
        # )
        # cancel_btn.pack(side=RIGHT, padx=5)

        # 应用按钮
        apply_btn = ttkb.Button(
            buttons_frame,
            text="应用",
            command=self.apply_settings,
            bootstyle=PRIMARY
        )
        apply_btn.pack(side=RIGHT, padx=5)

    def create_appearance_settings(self, parent):
        """创建外观设置内容"""
        frame = ttkb.LabelFrame(parent, text="外观设置", padding=10)
        frame.pack(fill=BOTH, expand=True, padx=10, pady=10)

        # 主题选择
        theme_frame = ttkb.Frame(frame)
        theme_frame.pack(fill=X, pady=5)

        ttkb.Label(theme_frame, text="主题:").pack(side=LEFT, padx=5)

        self.theme_var = tk.StringVar(value=self.settings['theme'])
        theme_combobox = ttkb.Combobox(
            theme_frame,
            textvariable=self.theme_var,
            values=ttkb.Style().theme_names(),
            width=20
        )
        theme_combobox.pack(side=LEFT, padx=5)

        # 字体选择
        font_frame = ttkb.Frame(frame)
        font_frame.pack(fill=X, pady=5)

        ttkb.Label(font_frame, text="字体:").pack(side=LEFT, padx=5)

        self.font_family_var = tk.StringVar(value=self.settings['font_family'])
        # 获取系统可用字体
        fonts = sorted(tk.font.families())
        font_combobox = ttkb.Combobox(
            font_frame,
            textvariable=self.font_family_var,
            values=fonts,
            width=20
        )
        font_combobox.pack(side=LEFT, padx=5)

        # 字体大小
        font_size_frame = ttkb.Frame(frame)
        font_size_frame.pack(fill=X, pady=5)

        ttkb.Label(font_size_frame, text="字体大小:").pack(side=LEFT, padx=5)

        self.font_size_var = tk.IntVar(value=self.settings['font_size'])
        font_size_spinbox = ttkb.Spinbox(
            font_size_frame,
            from_=8,
            to=24,
            increment=1,
            textvariable=self.font_size_var,
            width=5
        )
        font_size_spinbox.pack(side=LEFT, padx=5)

        # 允许缩放
        scaling_frame = ttkb.Frame(frame)
        scaling_frame.pack(fill=X, pady=5)

        self.allow_scaling_var = tk.BooleanVar(value=self.settings['allow_scaling'])
        scaling_check = ttkb.Checkbutton(
            scaling_frame,
            text="允许窗口缩放",
            variable=self.allow_scaling_var
        )
        scaling_check.pack(side=LEFT, padx=5)

    def create_system_settings(self, parent):
        """创建系统设置内容"""
        frame = ttkb.LabelFrame(parent, text="系统设置", padding=10)
        frame.pack(fill=BOTH, expand=True, padx=10, pady=10)

        # 系统名称
        name_frame = ttkb.Frame(frame)
        name_frame.pack(fill=X, pady=5)

        ttkb.Label(name_frame, text="系统名称:").pack(side=LEFT, padx=5)

        self.system_name_var = tk.StringVar(value=self.settings['system_name'])
        system_name_entry = ttkb.Entry(
            name_frame,
            textvariable=self.system_name_var,
            width=30
        )
        system_name_entry.pack(side=LEFT, padx=5, fill=X, expand=True)

        # 窗口大小
        window_size_frame = ttkb.LabelFrame(frame, text="窗口大小", padding=10)
        window_size_frame.pack(fill=X, pady=5)

        # 宽度
        width_frame = ttkb.Frame(window_size_frame)
        width_frame.pack(fill=X, pady=5)

        ttkb.Label(width_frame, text="宽度:").pack(side=LEFT, padx=5)

        self.window_width_var = tk.IntVar(value=self.settings['window_width'])
        width_spinbox = ttkb.Spinbox(
            width_frame,
            from_=600,
            to=1600,
            increment=50,
            textvariable=self.window_width_var,
            width=10
        )
        width_spinbox.pack(side=LEFT, padx=5)

        # 高度
        height_frame = ttkb.Frame(window_size_frame)
        height_frame.pack(fill=X, pady=5)

        ttkb.Label(height_frame, text="高度:").pack(side=LEFT, padx=5)

        self.window_height_var = tk.IntVar(value=self.settings['window_height'])
        height_spinbox = ttkb.Spinbox(
            height_frame,
            from_=400,
            to=1200,
            increment=50,
            textvariable=self.window_height_var,
            width=10
        )
        height_spinbox.pack(side=LEFT, padx=5)

        # 自动保存
        auto_save_frame = ttkb.Frame(frame)
        auto_save_frame.pack(fill=X, pady=5)

        self.auto_save_var = tk.BooleanVar(value=self.settings['auto_save'])
        auto_save_check = ttkb.Checkbutton(
            auto_save_frame,
            text="设置自动保存",
            variable=self.auto_save_var
        )
        auto_save_check.pack(side=LEFT, padx=5)

    def apply_saved_settings(self):
        """应用已保存的设置"""
        # 应用主题
        style = ttkb.Style()
        style.theme_use(self.settings['theme'])

        # 应用窗口缩放设置
        # if self.settings['allow_scaling']:
        #     self.resizable(True, True)
        # else:
        #     self.resizable(False, False)

    def apply_settings(self):
        """应用当前设置（不保存）"""
        # 应用主题
        style = ttkb.Style()
        style.theme_use(self.theme_var.get())

        # 应用窗口大小
        width = self.window_width_var.get()
        height = self.window_height_var.get()
        # self.root.geometry(f"{width}x{height}")

        # 应用窗口缩放设置
        allow_scaling = self.allow_scaling_var.get()
        # self.root.resizable(allow_scaling, allow_scaling)

        messagebox.showinfo("提示", "设置已应用")

    def save_settings(self):
        """保存设置到数据库"""
        # 更新设置字典
        updated_settings = {
            'id': 1,
            'theme': self.theme_var.get(),
            'font_family': self.font_family_var.get(),
            'font_size': self.font_size_var.get(),
            'window_width': self.window_width_var.get(),
            'window_height': self.window_height_var.get(),
            'allow_scaling': self.allow_scaling_var.get(),
            'system_name': self.system_name_var.get(),
            'auto_save': self.auto_save_var.get()
        }

        # 更新数据库
        self.settings_table.update(
            updated_settings,
            Query().id == 1
        )

        # 更新当前设置
        self.settings = updated_settings

        # 应用设置
        self.apply_settings()

        messagebox.showinfo("提示", "设置已保存")

    def create_widgets(self):
        pass
